<script setup lang="ts">
import { ref, reactive, PropType } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
//引入获取物流信息api
import { doGetLogisticsList, doGetLogisticsCompany } from '@/apis/freight/freightAdd'
//引入 获取未发货订单列表api
import { doGetBatchDeliveryPrice, dogetOrderNotDetailsByOrderNo } from '@/apis/order/index'
//引入商品发货api
import { doPutOrderDetailsByOrderNo } from '@/apis/order/index'
//引入type类型
import { OrderDetail, ILogistics, ShopOrderItems, IOrder, LogisticsType } from '../type'
//引入获取物流信息的模块
import AreaShow from '@/components/area/area-show.vue'
import { useShopDetail } from '@/store/modules/shopdetail/index'
import { IcFreightFee } from '@/apis/order/sameCityOrder/types'

const { divTenThousand } = useConvert()
const emits = defineEmits(['changeShow'])
const shopstore = useShopDetail()
const props = defineProps({
    sendDialogShow: {
        type: Boolean,
        default: false,
    },
    order: {
        type: Object as () => IOrder,
        default: () => ({}),
    },
    deliverTypeList: {
        type: Array as PropType<
            {
                label: string
                value: 'IC_MERCHANT' | 'IC_OPEN'
            }[]
        >,
        default: () => [],
    },
})
//控制多选框是否选中
const checked = ref(true)
//下拉选择数据
const value = ref(0)
// 下拉选择发货方式数据
const SendDataRange = reactive([
    { value: 'EXPRESS', text: '手动发货' },
    { value: 'PRINT_EXPRESS', text: '打印快递单并发货' },
])
// 下拉选择物流公司数据
const LogisticsRange = ref<ILogistics[]>([])
//订单数据
const orderDetail = reactive<OrderDetail>({
    deliverType: 'EXPRESS',

    dropDeliver: true,
    expressCompany: {
        expressCompanyCode: '',
        expressCompanyName: '',
        expressNo: '',
    },
    items: [],
    receiver: {
        address: '',
        mobile: '',
        name: '',
    },
    sender: {
        address: '',
        mobile: '',
        name: '',
    },
    cargo: '',
})
const shopOrderItems = ref<ShopOrderItems[]>([])
const createTime = ref('')
const address = ref('')
//物流信息
const logistics = ref({
    name: '',
    code: '',
})
//储存地址
const areaList = ref<string[]>([])
//存储发货的地址
const addressList = ref<LogisticsType[]>([])

enum DISTRIBUTION {
    MERCHANT,
    EXPRESS, //快递配送
    INTRA_CITY_DISTRIBUTION, //同城配送
    SHOP_STORE, //店铺门店
    VIRTUAL, // 无需物流
}
const distributionModeStatus: Record<keyof typeof DISTRIBUTION, string> = {
    MERCHANT: '快递配送',
    EXPRESS: '快递配送',
    INTRA_CITY_DISTRIBUTION: '同城配送',
    SHOP_STORE: '门店自提',
    VIRTUAL: '无需物流',
}

//

onLoad(async () => {
    // console.log('props', props.order)
})

/**
 * 点击取消发货
 */
const handleShowGoodSend = () => {
    //清空shopStore中的数据
    emits('changeShow')
}
/**
 * 点击发货
 */
const handleGoodSend = async () => {
    if (props.order.distributionMode === 'VIRTUAL') {
        orderDetail.deliverType = 'WITHOUT'
    }
    if (props.order.distributionMode === 'INTRA_CITY_DISTRIBUTION') {
        console.log(orderDetail)
        // orderDetail.deliverType = 'IC_MERCHANT'
        // orderDetail.deliverType = 'IC_OPEN'
        Reflect.deleteProperty(orderDetail, 'expressCompany')
    }
    //判断如果是门店订单就不能发货

    //判断表单数据是否填写完整
    if (orderDetail.deliverType === 'EXPRESS') {
        if (orderDetail.expressCompany) {
            if (orderDetail.expressCompany.expressCompanyCode === '' || orderDetail.expressCompany.expressCompanyName === '') {
                uni.showToast({
                    title: '请选择物流公司',
                    icon: 'none',
                    duration: 2000,
                })
                return
            }
            if (orderDetail.expressCompany.expressNo === '') {
                uni.showToast({
                    title: '请填写物流单号',
                    icon: 'none',
                    duration: 2000,
                })
                return
            }
            if (orderDetail.items.length === 0) {
                uni.showToast({
                    title: '请选择商品',
                    icon: 'none',
                    duration: 2000,
                })
                return
            }
        }
    }
    if (orderDetail.deliverType === 'WITHOUT') {
        orderDetail.expressCompany = null
        if (orderDetail.items.length === 0) {
            uni.showToast({
                title: '请选择商品',
                icon: 'none',
                duration: 2000,
            })
            return
        }
    }
    if (orderDetail.deliverType === 'PRINT_EXPRESS') {
        if (orderDetail.expressCompany) {
            if (orderDetail.expressCompany.expressCompanyCode === '' || orderDetail.expressCompany.expressCompanyName === '') {
                uni.showToast({
                    title: '请选择物流公司',
                    icon: 'none',
                    duration: 2000,
                })
                return
            }
            if (orderDetail.sender.address === '') {
                uni.showToast({
                    title: '请填写发货地址',
                    icon: 'none',
                    duration: 2000,
                })
                return
            }
        }
    }
    // 发货成功需要重新请求未发货订单列表
    const data = await doPutOrderDetailsByOrderNo(props.order.orderNo, orderDetail)

    if (data.code === 200) {
        uni.showToast({
            title: '发货成功',
            icon: 'none',
            duration: 2000,
        })

        uni.$emit('update')
    } else {
        uni.showToast({
            title: data.msg || '发货失败',
            icon: 'none',
            duration: 2000,
        })
    }
    //清空shopStore中的数据
    emits('changeShow')
}
/**
 *  点击下拉选择发货方式
 */
const handleChangeSelector = (e: any) => {
    orderDetail.deliverType = e
    let arr: ILogistics[] = []
    if (e === 'PRINT_EXPRESS') {
        addressList.value.forEach((item, index) => {
            arr[index] = {
                value: {
                    address: areaList.value[index] + item.contactName,
                    mobile: item.contactPhone,
                    name: item.contactName,
                },
                text: areaList.value[index],
            }
        })
        addressArr.value = arr
    }
}
/**
 * 点击下拉选择物流公司
 */
const handleChangeLogistics = (e: any) => {
    //收集选择的物流信息
    if (orderDetail.deliverType === 'EXPRESS' || orderDetail.deliverType === 'PRINT_EXPRESS') {
        if (orderDetail.expressCompany) {
            orderDetail.expressCompany.expressCompanyCode = e.code
            orderDetail.expressCompany.expressCompanyName = e.name
        }
    }
    console.log(e, orderDetail.expressCompany)
}
const handleChangeArea = (e: any) => {
    orderDetail.sender.address = e.address
    orderDetail.sender.name = e.name
    orderDetail.sender.mobile = e.mobile
}
/**
 * 获取发货的物流信息
 */
const LogisticsArr = ref<string[][]>([])
const addressArr = ref<
    {
        value: {
            address?: string
            name: string
            mobile?: string
        }
        text: string
    }[]
>([])
//缺少打印机信息
const handleGetLogistics = async () => {
    const res = await doGetLogisticsList({})
    let arr = []

    if (res.code === 200) {
        arr = res.data.records.map((item: any, index: number) => {
            return [item.provinceCode, item.cityCode, item.regionCode]
        })
    }
    LogisticsArr.value = arr
    addressList.value = res.data.records
}

/**
 * 获取物流公司列表
 */
const GetFMSList = async () => {
    const res = await doGetLogisticsCompany()
    //LogisticsRange.value是一个数组 取出res.data.records中的expressCompanyName和expressCompanyCode组成对象放进LogisticsRange.value每一项
    res.data.records.forEach((item: any, index: number) => {
        LogisticsRange.value[index] = {
            value: {
                code: item.logisticsCompanyCode,
                name: item.logisticsCompanyName,
            },

            text: item.logisticsCompanyName,
        }
    })
}
/**
 * 获取未发货订单列表
 */
const GetOrderList = async () => {
    const res = await dogetOrderNotDetailsByOrderNo(props.order.orderNo, props.order.shopOrderNo)
    //储存订单创建时间
    createTime.value = res.data.orderReceiver.createTime
    //储存 未发货订单列表
    shopOrderItems.value = res.data.shopOrderItems.filter((item: any) => item.sellType !== 'CONSIGNMENT')
    console.log('shopOrderItems', shopOrderItems.value)
    //储存 地址信息

    address.value = `${res.data.orderReceiver.name},${res.data.orderReceiver.mobile},${res.data.orderReceiver.area.join('')}${
        res.data.orderReceiver.address
    }`
    orderDetail.receiver = res.data.orderReceiver
    orderDetail.items = res.data.shopOrderItems.map((item) => {
        return { itemId: item.id, num: item.num }
    })
}

/**
 * 选择需要发货的商品 多选组件回调函数
 */
const checkboxChange = (e: any) => {
    //收集选择的商品信息
    //e.detail.value取消proxy响应式
    orderDetail.items = JSON.parse(JSON.stringify(e.detail.value))
}

const handleChangeAreaa = (e: any) => {
    areaList.value.push(e)
}
GetOrderList()
GetFMSList()
handleGetLogistics()

const freightFee = ref<IcFreightFee>({
    balance: 0,
    orderPriceMap: {
        [props.order.orderNo]: {
            discount: 0,
            pay: 0,
            total: 0,
        },
    },
    totalPrice: 0,
})
const deliverTypeChange = async (e: 'IC_MERCHANT' | 'IC_OPEN') => {
    console.log(e)
    if (e === 'IC_OPEN') {
        const { data } = await doGetBatchDeliveryPrice([props.order.orderNo])
        freightFee.value = data!
    }
}
</script>

<template>
    <template v-for="item in LogisticsArr" :key="item">
        <AreaShow v-if="props.order.distributionMode === 'EXPRESS'" :areacode="item" @changearea="handleChangeAreaa"> </AreaShow>
    </template>
    <!-- 发货弹窗部分 -->
    <u-popup :model-value="props.sendDialogShow" class="popup" mode="bottom" border-radius="14" appendToBody>
        <view class="popup-btn">
            <view class="popup-btn__left" @click="handleShowGoodSend"> 取消</view>
            <view class="popup-btn__right" @click="handleGoodSend"> 发货</view>
        </view>
        <scroll-view style="height: 800rpx" :scroll-y="true" @touchmove.stop>
            <view class="datalist">
                <view class="datalist__shopdetail shopdetail">
                    <view class="shopdetail__title">商品信息</view>
                    <view class="shopdetail__detail">
                        <scroll-view class="scroll" :scroll-y="true" @touchmove.stop>
                            <checkbox-group @change="checkboxChange">
                                <template v-for="item in shopOrderItems" :key="item">
                                    <view class="scrollitem">
                                        <view class="check">
                                            <checkbox
                                                :value="{ itemId: item.id, num: item.num }"
                                                :checked="checked"
                                                :disabled="['VIRTUAL', 'INTRA_CITY_DISTRIBUTION'].includes(props.order.distributionMode)"
                                            />
                                        </view>
                                        <view class="shopdetail__detail--img">
                                            <u-image width="130rpx" height="130rpx" :src="item.image"></u-image>
                                        </view>
                                        <view class="shopdetail__detail--data">
                                            <view class="shopdetail__detail--datatitle">{{ item.productName }}</view>
                                            <view class="shopdetail__detail--total">
                                                <template v-if="item.specs">
                                                    <view class="item__attributelist">
                                                        <template v-for="t in item.specs" :key="t">
                                                            <view class="item__attribute"> {{ t }}</view>
                                                        </template>
                                                    </view>
                                                </template>
                                                <view>×{{ item.num }}</view>
                                            </view>
                                            <view style="color: #999999">￥{{ (item.dealPrice / 10000).toFixed(2) }}</view>
                                        </view>
                                    </view>
                                </template>
                            </checkbox-group>
                        </scroll-view>
                    </view>
                </view>

                <view class="datalist__shopdetail shopdetail">
                    <view class="shopdetail__title">订单号</view>
                    <view class="shopdetail__detail">{{ props.order.orderNo }}</view>
                </view>
                <view class="datalist__shopdetail shopdetail">
                    <view class="shopdetail__title">创建时间</view>
                    <view class="shopdetail__detail">{{ createTime }}</view>
                </view>
                <view class="datalist__shopdetail shopdetail">
                    <view class="shopdetail__title">收货地址</view>
                    <view class="shopdetail__detail">{{ address }}</view>
                </view>
                <view class="datalist__shopdetail shopdetail">
                    <view class="shopdetail__title">配送方式</view>
                    <view class="shopdetail__detail">{{ distributionModeStatus[props.order.distributionMode] }}</view>
                </view>
                <view v-if="props.order.distributionMode === 'EXPRESS'">
                    <view class="datalist__shopdetail shopdetail">
                        <view class="shopdetail__title">发货方式</view>

                        <view class="shopdetail__detail dorpdowns">
                            <uni-data-select
                                v-model="value"
                                placeholder="请选择发货方式"
                                :localdata="SendDataRange"
                                style="border: none"
                                @change="handleChangeSelector"
                            ></uni-data-select>
                        </view>
                    </view>
                    <template v-if="orderDetail.deliverType === 'EXPRESS' || orderDetail.deliverType === 'PRINT_EXPRESS'">
                        <view class="datalist__shopdetail shopdetail">
                            <view class="shopdetail__title">物流公司</view>
                            <view class="shopdetail__detail dorpdowns">
                                <uni-data-select
                                    v-model="logistics"
                                    placeholder="请选择物流公司"
                                    :localdata="LogisticsRange"
                                    style="border: none"
                                    @change="handleChangeLogistics"
                                ></uni-data-select>
                            </view>
                        </view>
                    </template>
                    <template v-if="orderDetail.deliverType === 'EXPRESS'">
                        <view class="datalist__shopdetail shopdetail">
                            <view class="shopdetail__title">物流单号</view>
                            <view class="shopdetail__detail dorpdowns">
                                <u-input
                                    v-model="orderDetail.expressCompany!.expressNo"
                                    style="text-indent: 20rpx"
                                    placeholder="请输入物流单号"
                                ></u-input>
                            </view>
                        </view>
                    </template>
                    <template v-if="orderDetail.deliverType === 'PRINT_EXPRESS'">
                        <view class="datalist__shopdetail shopdetail">
                            <view class="shopdetail__title">发货地址</view>
                            <view class="shopdetail__detail dorpdowns">
                                <uni-data-select
                                    v-model="orderDetail.sender"
                                    placeholder="请选择发货地址"
                                    :localdata="addressArr"
                                    style="border: none"
                                    @change="handleChangeArea"
                                ></uni-data-select>
                            </view>
                        </view>
                    </template>
                </view>
                <template v-else-if="props.order.distributionMode === 'INTRA_CITY_DISTRIBUTION'">
                    <view class="datalist__shopdetail shopdetail">
                        <view class="shopdetail__title">配送方</view>
                        <uni-data-select
                            v-model="orderDetail.deliverType"
                            class="shopdetail__detail dorpdowns"
                            placeholder="请选择配送方"
                            :localdata="deliverTypeList"
                            format="{label}"
                            @change="deliverTypeChange"
                        ></uni-data-select>
                    </view>
                    <view v-if="orderDetail.deliverType === 'IC_OPEN'" class="datalist__shopdetail shopdetail">
                        <view class="shopdetail__title">预估价</view>
                        <view class="shopdetail__detail dorpdowns">
                            <view class="tips fcenter">
                                <view class="red">预估 {{ divTenThousand(freightFee.totalPrice) }}元</view>
                                <view style="display: flex">
                                    <view>优惠</view>
                                    <view>￥{{ divTenThousand(freightFee?.orderPriceMap?.[props.order.orderNo]?.discount || 0) }}</view>
                                </view>
                                <view style="display: flex">
                                    <view>应付</view>
                                    <view>￥{{ divTenThousand(freightFee?.orderPriceMap?.[props.order.orderNo]?.pay || 0) }}</view>
                                </view>
                                <view style="display: flex">
                                    <view>合计</view>
                                    <view>￥{{ divTenThousand(freightFee?.orderPriceMap?.[props.order.orderNo]?.total || 0) }}</view>
                                </view>
                            </view>
                        </view>
                    </view>
                </template>
                <template v-else>
                    <span style="color: #f00">您可通过网络形式(如:聊天工具将商品发给用户)发货</span>
                </template>

                <view style="height: 350rpx"></view>
            </view>
        </scroll-view>
    </u-popup>
</template>

<style lang="scss" scoped>
@include b(popup) {
    display: flex;
    flex-direction: column;
}

@include b(popup-btn) {
    height: 92rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 30rpx;
    color: #101010;
    font-size: 28rpx;
    border-bottom: 1px solid rgba(245, 245, 245, 1);

    @include e(right) {
        color: rgba(71, 85, 233, 1);
    }
}

@include b(scrollitem) {
    display: flex;
    height: 130rpx;
}

@include b(scroll) {
    height: 130rpx;
    border: 1px solid rgb(211, 210, 210);
    padding: 20rpx;
    border-radius: 20rpx;
}

@include b(datalist) {
    display: flex;
    flex-direction: column;
    padding: 32rpx 28rpx 28rpx 32rpx;
    font-size: 26rpx;
}

@include b(shopdetail) {
    display: flex;
    align-items: center;

    margin-bottom: 50rpx;

    @include e(title) {
        width: 110rpx;
        margin-right: 36rpx;
        text-align: right;
    }

    @include e(detail) {
        width: 544rpx;
        flex: 1;
        display: flex;
        @include m(datatitle) {
            // width: 365rpx;
            height: 68rpx;
            //多行文字第二行溢出省略号
            @include utils-ellipsis(2);
        }

        @include m(img) {
            width: 130rpx;
            height: 130rpx;
            margin-right: 18rpx;
        }

        @include m(total) {
            display: flex;
            justify-content: space-between;
            color: #999999;
        }

        @include m(data) {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
        }
    }
}

@include b(dorpdowns) {
    width: 546rpx;
    height: 64rpx;
    border-radius: 10rpx;
    background-color: rgba(255, 255, 255, 1);
    color: rgba(65, 80, 88, 1);
    font-size: 24rpx;
    font-family: Microsoft Yahei;
    border: 2rpx solid rgba(204, 204, 204, 1);
}

@include b(check) {
    display: flex;
    align-items: center;
    justify-content: center;
}

:deep(.uni-select) {
    border: none;
}
</style>
